from rest_framework import serializers
from ..models import Article,FileUpload
from django.contrib.auth import get_user_model

User = get_user_model()

class UserSerializer(serializers.ModelSerializer):
    password = serializers.HiddenField(default='lmg')
    date_joined=serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False, read_only=True)
    # articles = serializers.PrimaryKeyRelatedField(many=True, read_only=True)
    # articles = serializers.StringRelatedField(many=True, read_only=True)
    # articles = serializers.HyperlinkedRelatedField(many=True, read_only=True,view_name='article-detail')

    class Meta:
        model=User
        fields=("id","username","email","is_staff","is_active","date_joined","first_name","last_name","password",) #"articles",
        # fields = '__all__'
        read_only_fields = ('id', "date_joined",)

class ArticleSerializer(serializers.ModelSerializer):

    # author = serializers.HiddenField(default=serializers.CurrentUserDefault())
    author = serializers.ReadOnlyField(source="author.username")
    # status = serializers.ReadOnlyField(source="get_status_display")
    # full_status = serializers.ReadOnlyField(source="get_status_display")
    # author = UserSerializer(read_only=True) # required=False表示可接受匿名用户，many=True表示有多个用户。
    cn_status = serializers.SerializerMethodField()
    create_date = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False, read_only=True)

    def validate_title(self, value):
            """
            Check that the article is about Django.
            """
            if 'Django'  in value.lower():
                raise serializers.ValidationError("Article is  about Django")
            return value

    def get_cn_status(self, obj):
        if obj.status == 'p':
            return "已发表"
        elif obj.status == 'd':
            return "草稿"
        else:
            return ''
        
    # def to_representation(self, value):
    #     # 调用父类获取当前序列化数据，value代表每个对象实例ob
    #     data = super().to_representation(value)
    #     # 对序列化数据做修改，添加新的数据
    #     data['total_likes'] = value.liked_by.count()
    #     return data

    class Meta:
        model = Article
        depth = 1 # 注意这里
        fields = '__all__'
        read_only_fields = ('id', 'author', 'create_date',)

class FileUploadSerializer(serializers.ModelSerializer):
    create_date = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False, read_only=True)
    author = serializers.ReadOnlyField(source="author.username")
    
    class Meta:
        model = FileUpload
        fields = '__all__'
        read_only_fields = ('id', 'author', 'create_date',)